// finger 服务 6. 从空的 UserMap 里查找用户。
// 从一行里拿到用户名，在 UserMap 中查找，然后返回结果。
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpServer.h>
#include <map>

using namespace muduo;
using namespace muduo::net;

typedef std::map<string, string> UserMap;
UserMap users;

string // this is muduo::string
GetUser(const string &user) {
	string result = "No such user";
	UserMap::iterator it = users.find(user);
	if (it != users.end())
		result = it->second;
	return result;
}

void
OnMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp receiveTime) {
	const char *crlf = buf->findCRLF();
	if (crlf) {
		string user(buf->peek(), crlf);
		conn->send(GetUser(user) + "\r\n");
		buf->retrieveUntil(crlf + 2);
		conn->shutdown();
	}
}

int
main() {
	users["u1"] = "u1info";
	users["u2"] = "u2info";

	EventLoop loop;
	TcpServer server(&loop, InetAddress(1079), "Finger");
	server.setMessageCallback(OnMessage);
	server.start();
	loop.loop();
	return 0;
}
